# -*- coding: utf-8 -*-
import json
data = '{"success": true,"sort": "热歌榜","info": [{"id": 1,"name": "风"},{"id": 2,"name": "雨"}]}'
obj = {'success': True, 'sort': '热歌榜', 'info': [{'id': 1, 'name': '风'}, {'id': 2, 'name': '雨'}]}

"""
json字符串和内置对象之间的转换
"""
json.loads(data)  # 将json字符串转换成对象,从json文件中读取为json.load(file)
json.dumps(obj, ensure_ascii=False)  # 将对象转换成json字符串,ensure_ascii为True时中文将转为Unicode码,保存到文件为json.dumps(obj, file)


"""
json字符串和自定义实体对象之间的转换
"""
class MusicBean(object):
    def __init__(self, d):
        self.__dict__ = d

    def __str__(self):
        return str(self.__dict__)

mb = json.loads(data, object_hook=MusicBean)  # 将json字符串转换成实体对象
print(mb.info[1])
js = json.dumps(mb, default=lambda o: o.__dict__)
print(js)